﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace Fulcrum.ControlGenerator
{
    [Export(typeof(GenerationUnit))]
    public class ControlGeneratorGenerationUnit : GenerationUnit
    {
        ControlGeneratorSettings settings;
        List<GenerationDataContext> dataContexts;

        public ControlGeneratorGenerationUnit() :
            base("ControlGenerator")
        {
            this.settings = new ControlGeneratorSettings();
            this.Settings = this.settings;
        }

        public override void CreateDataContexts()
        {
            LoadConfigFile();
        }

        void LoadConfigFile()
        {
            var config = GetConfiguration();

            this.dataContexts = new List<GenerationDataContext>();

            if (String.IsNullOrEmpty(this.settings.Control))
            {
                foreach (var controlConfig in config.ControlConfigurations)
                {
                    var dataContext = new ControlGeneratorGenerationDataContext(config, controlConfig);
                    this.dataContexts.Add(dataContext);
                }
            }
            else
            {
                var controlConfig = config.GetControlConfiguration(this.settings.Control);
                var dataContext = new ControlGeneratorGenerationDataContext(config, controlConfig);
                this.dataContexts.Add(dataContext);
            }
        }

        protected virtual IControlGeneratorConfiguration GetConfiguration()
        {
            var config = new ControlGeneratorXmlConfiguration(this.settings.ConfigFileName);

            return config;
        }

        public override ICollection<GenerationDataContext> DataContexts
        {
            get
            {
                return this.dataContexts;
            }
        }
    }
}
